import numpy as np
from sklearn.linear_model import LinearRegression #线性回归

if __name__ == '__main__':
    #特征值
    # 原数据，用 array 替代 mat，更推荐
    x = np.array([[80, 86],
                  [82, 80],
                  [85, 70],
                  [90, 90],
                  [86, 82],
                  [82, 90],
                  [78, 80],
                  [92, 94]], dtype=float)

    y = np.array([84.2, 80.6, 80.1, 90, 83.2, 87.6, 79.4, 93.4], dtype=float).reshape(-1, 1)

    # 增加截距项
    ones = np.ones((x.shape[0], 1), dtype=float)
    X = np.hstack([ones, x])  # shape (8,3)

    # 正规方程解：w = (X^T X)^(-1) X^T y
    XtX = X.T @ X
    XtX_inv = np.linalg.inv(XtX)
    w = XtX_inv @ X.T @ y  # 结果 (3,1)

    # 打印参数
    a, b, c = w[:, 0]  # 解嵌套一层
    print(f"[{a:.1f} {b:.1f} {c:.1f}]")

    #使用LinearRegression求解
    estimator = LinearRegression(fit_intercept=True)
    estimator.fit(x, y)
    print(estimator.coef_[0])